<?php
namespace app\model;

use think\Model;

class DeviceData extends Model
{
    // 设置数据表名
    protected $name = 'device_data';
    
    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'device_id'   => 'int',
        'data_type'   => 'string',
        'data_value'  => 'string',
        'unit'        => 'string',
        'is_alarm'    => 'tinyint',
        'alarm_type'  => 'tinyint',
        'alarm_threshold' => 'string',
        'data_time'   => 'datetime',
        'create_time' => 'datetime',
    ];
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    
    // 关闭自动写入update_time
    protected $updateTime = false;
    
    // 关联设备
    public function device()
    {
        return $this->belongsTo(Device::class, 'device_id');
    }
    
    // 告警类型获取器
    public function getAlarmTypeTextAttr()
    {
        $types = [
            0 => '正常',
            1 => '警告',
            2 => '一般',
            3 => '严重',
            4 => '紧急'
        ];
        return $types[$this->alarm_type] ?? '未知';
    }
    
    // 搜索设备ID
    public function searchDeviceIdAttr($query, $value)
    {
        if (is_numeric($value)) {
            $query->where('device_id', $value);
        }
    }
    
    // 搜索数据类型
    public function searchDataTypeAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('data_type', $value);
        }
    }
    
    // 搜索是否告警
    public function searchIsAlarmAttr($query, $value)
    {
        if (is_numeric($value)) {
            $query->where('is_alarm', $value);
        }
    }
    
    // 搜索告警类型
    public function searchAlarmTypeAttr($query, $value)
    {
        if (is_numeric($value)) {
            $query->where('alarm_type', $value);
        }
    }
    
    // 搜索时间范围
    public function searchTimeRangeAttr($query, $value)
    {
        if (!empty($value) && is_array($value) && count($value) == 2) {
            $query->whereTime('data_time', 'between', $value);
        }
    }
    
    // 统计指定时间段内的数据
    public static function getStatsByTimeRange($deviceId, $dataType, $startTime, $endTime, $interval = 'hour')
    {
        $query = self::where('device_id', $deviceId)
            ->where('data_type', $dataType)
            ->whereTime('data_time', 'between', [$startTime, $endTime]);
        
        switch ($interval) {
            case 'minute':
                $format = '%Y-%m-%d %H:%i';
                break;
            case 'hour':
                $format = '%Y-%m-%d %H:00';
                break;
            case 'day':
                $format = '%Y-%m-%d';
                break;
            case 'month':
                $format = '%Y-%m';
                break;
            default:
                $format = '%Y-%m-%d %H:00';
        }
        
        $result = $query->field([
            "DATE_FORMAT(data_time, '{$format}') as time_point",
            'AVG(data_value) as avg_value',
            'MAX(data_value) as max_value',
            'MIN(data_value) as min_value',
            'COUNT(*) as count'
        ])->group('time_point')->order('time_point')->select();
        
        return $result;
    }
} 